var _parentWindow = window.parent || window.top || window.opener

window.$tokenProcess =
  window.$tokenProcess ||
  function($http) {
    // 10秒激活刷新 Token
    setInterval(function() {
      window.$callParent('RefreshToken')
    }, 10 * 1000)

    function getToken() {
      return _parentWindow.localStorage.Authorization
    }

    // 为所有 Ajax 设置 header
    var lastToken
    function setTokenToHeader() {
      var newToken = getToken()
      if (newToken !== lastToken) {
        lastToken = newToken
        $http.defaults.headers.common['authorization'] = 'Bearer ' + newToken
        $http.defaults.headers.common['tenant'] = localStorage.tenant || ''
        jQuery.ajaxSetup({
          headers: {
            authorization: 'Bearer ' + newToken,
            tenant: localStorage.tenant
          }
        })
      }
    }

    setTokenToHeader()
    window.$registerMessageHandler('SendToken', setTokenToHeader)
  }

window.$callParent = function(message, targetOrigin, transfer) {
  targetOrigin = targetOrigin || location.origin
  _parentWindow.postMessage(message, targetOrigin, transfer)
}

var _messageHandler = {}
window.$registerMessageHandler = function(eventType, handler) {
  _messageHandler[eventType] = handler
}

window.addEventListener('message', function(event) {
  let origin = event.origin || event.originalEvent.origin
  if (origin !== location.origin) {
    return
  }

  var handler = _messageHandler[event.data]
  handler && handler()
})
